<?php
/*
 * 权限生成工具
 * @since 1.0 2014-7-11 by sutroon
 * @since 1.1 <2015-7-30> SoChishun 独立为新项目
 * @since 1.2 <2015-10-19> SoChishun 新增起始编号,Addon模板等
 */
// 版本号
$ver = '1.0';

/**
 * 全局项目配置
 * <br />字段模板与节点键名一样, 固定字段模板：{id}:主键编号, {parent_id}:父级编号, {parent_code}:父级代码, {type}:节点类型, {sort}:排序, 
 * @since 1.0 <2015-7-30> SoChishun Added.
 * @since 1.1 <2015-8-4> SoChishun 新增url_prefix选项
 * @since 1.2 <2015-9-19> SoChishun 重构,去除url_prefix选项
 * @since 1.3 <2015-11-11> SoChishun 新增message
 */
$config = array(
    'Test' => array(
        'tmp_sql' => 'insert into tuser_permission (id, `name`, parent_id, code, link_url, ordinal, is_menu)',
        'url_prefix' => '/xcall',
        'path' => '',
    ),
    'Addon' => array(
        'var' => array('{id}' => array('type' => 'string', 'default' => ''), '{name}' => array('type' => 'string', 'default' => ''), '{title}' => array('type' => 'string', 'default' => ''), '{parent_id}' => array('type' => 'string', 'default' => ''), '{code}' => array('type' => 'string', 'default' => ''), '{sort}' => array('type' => 'string', 'default' => ''), '{url}' => array('type' => 'string', 'default' => ''), '{type}' => array('type' => 'string', 'default' => 'M'), '{level}' => array('type' => 'string', 'default' => '0')),
        'sql' => "insert into think_auth_rule (`id`, `name`, `title`, `pid`, `addon`, `code`, `sort`, `url`, `type`, `level`,`status`) values ({id},'{name}','{title}','{parent_id}','{addon}','{code}',{sort},'{url}','{type}',{level},1);",
        'path' => 'F:\PDC\ProjectEnv\SuOSP\xwamp_php_2_0\Application\XWAM\Addon\{addon}\Install\Data\Permission.php',
        'addon_root' => '../../../Application/XWAM/Addon',
        'message' => '通用插件范例',
    ),
    'XCrm' => array(
        'var' => array('{id}' => array('type' => 'string', 'default' => ''), '{name}' => array('type' => 'string', 'default' => ''), '{title}' => array('type' => 'string', 'default' => ''), '{parent_id}' => array('type' => 'string', 'default' => ''), '{code}' => array('type' => 'string', 'default' => ''), '{sort}' => array('type' => 'string', 'default' => ''), '{url}' => array('type' => 'string', 'default' => ''), '{type}' => array('type' => 'string', 'default' => 'M'), '{level}' => array('type' => 'string', 'default' => '0')),
        'sql' => "insert into think_auth_rule (`id`, `name`, `title`, `pid`, `addon`, `code`, `sort`, `url`, `type`, `level`,`status`) values ({id},'{name}','{title}','{parent_id}','{addon}','{code}',{sort},'{url}','{type}',{level},1);",
        'path' => 'F:\PDC\ProjectEnv\SuOSP\xwamp_case\xwamp_php_final\Application\XWAM\ProjectResourceLibrary\Install\Permission.php',
        'message' => 'XCrm项目',
    ),
    'PXCallSystem' => array(
        'var' => array('{id}' => array('type' => 'string', 'default' => ''), '{name}' => array('type' => 'string', 'default' => ''), '{title}' => array('type' => 'string', 'default' => ''), '{parent_id}' => array('type' => 'string', 'default' => ''), '{code}' => array('type' => 'string', 'default' => ''), '{sort}' => array('type' => 'string', 'default' => ''), '{url}' => array('type' => 'string', 'default' => ''), '{type}' => array('type' => 'string', 'default' => 'M'), '{level}' => array('type' => 'string', 'default' => '0')),
        'sql' => "insert into think_auth_rule (`id`, `name`, `title`, `pid`, `addon`, `code`, `sort`, `url`, `type`, `level`,`status`) values ({id},'{name}','{title}','{parent_id}','PXCallSystem','{code}',{sort},'{url}','{type}',{level},1);",
        'path' => 'F:\PDC\ProjectEnv\SuOSP\XWAMP_PHP_1_0\Application\XWAM\Addon\PXCallSystem\Install\Data\Permission_auth.php',
        'message' => 'PXCallSystem整站项目',
    ),
    'XWAM_1_0' => array(
        'sql_field' => 'insert into tuser_permission (id, permission_name, permission_code, parent_code, ordinal, link_url, is_menu) values ',
        'sql_value' => "({id}, '{name}','{code}','{parent_code}',{sort},'{url}','{ismenu}');",
        'path' => 'F:\PDC\ProjectEnv\xcall150505\Application\XWAM\ProjectResourceLibrary\SqlScript\PermissionData.php',
    )
);

/**
 * 生成SQL
 * @param string $name 项目名称
 * @param array $config 配置文件
 * @since 1.0 <2015-7-30> SoChishun Added.
 */
function make_sql($name, $config) {
    if (!array_key_exists($name, $config)) {
        echo '配置文件不存在!';
        exit;
    }
    $path = $config[$name]['path'];
    if (!$path) {
        echo '配置路径无效';
        exit;
    }
    if (!file_exists($path) || !is_file($path)) {
        echo '路径不存在或不是有效文件';
        exit;
    }
    $permission_data = require $path;
    if (!is_array($permission_data)) {
        die('权限内容无效!');
    }
    generate_insert_sql($permission_data, $config[$name], 1);
}

/**
 * 获取url变量
 * @param type $name
 * @param type $defv
 * @return type
 * @since 1.0 <2015-7-30> SoChishun Added.
 */
function I($name, $defv = '') {
    return isset($_GET[$name]) ? $_GET[$name] : $defv;
}

$name = I('proj', 'Demo');
$addon = I('addon');
if ('Addon' == $name) {
    if (!$addon) {
        exit('插件名称无效!');
    }
    $config[$name]['path'] = str_replace('{addon}', $addon, $config[$name]['path']);
    $config[$name]['sql'] = str_replace('{addon}', $addon, $config[$name]['sql']);
}
$i = I('start_id', 1);
?>
<!DOCTYPE html>
<html>
    <head>
        <title>SoPermissionSql-<?php echo $ver ?></title>
        <meta charset="UTF-8">
        <style type='text/css'>
            body { font-size:12px;}
            p{margin:0px; color:#555;}
            th { font-size:12px; font-weight: normal; text-align: left;}
        </style>
    </head>
    <body>
        <form>
            <table>
                <tr><th>选择项目：</th><td>
                        <?php
                        echo '<select name="proj">';
                        foreach ($config as $key => $value) {
                            echo '<option value="', $key, '"', ($name == $key ? ' selected="selected"' : ''), ' title="' . (array_key_exists('message', $value) ? $value['message'] : '') . '">', $key, '</option>';
                        }
                        echo '<select>';
                        ?>                        
                    </td></tr>
                <tr><th>插件名称：</th><td><input type="text" id="addon" name="addon" value="<?php echo $addon ?>" />
                        <?php
                        if (isset($config['Addon'])) {
                            get_addon_combobox($config['Addon']['addon_root'], $addon);
                        }
                        ?>
                    </td></tr>
                <tr><th valign="top">起始编号：</th><td><p>通过 select max(id)+1 from think_auth_rule; 查询</p><input type="text" name="start_id" value="<?php echo $i ?>" size="3" /></td></tr>
            </table>
            <button type="submit">立即生成</button><button type="reset">重置</button>
        </form>
        <?php
        // 生成语句
        $ids = array();
        echo '<textarea cols="136" rows="35">';
        make_sql($name, $config);
        echo '</textarea>';
        echo '<br /><textarea cols="136" rows="4">' . implode(',', $ids) . '</textarea>';

        /**
         * 生成权限表的插入语句
         * @global int $i 主键编号变量
         * @global type $ids 编号集合
         * @param type $permissions 权限规则数组
         * @param type $config 配置
         * @param type $n 父级编号
         * @param type $parentcode 父级代码
         * @param type $type 节点类型
         * @since 1.0 2014-7-11 by sutroon
         * @since 1.1 <2015-8-28> SoChishun 新增parentcode参数
         * @since 2.0 <2015-9-22> SoChishun 重构,适配RBAC概念
         * @example generate_insert_sql($arr, 1);
         */
        function generate_insert_sql($permissions, $config, $n, $parentcode = '') {
            global $i, $ids;
            if (!$i) {
                $i = 1;
            }
            $sql = $config['sql'];
            foreach ($permissions as $arow) {
                if (isset($arow['enable']) && !$arow['enable']) {
                    continue;
                }
                // 固定替换占位符
                $const_replaces = array(
                    '{id}' => $i,
                    '{parent_id}' => $n - 1,
                    '{parent_code}' => $parentcode,
                    '{sort}' => $i,
                );
                $vars = $config['var'];
                foreach ($vars as $key => &$value) {
                    if (array_key_exists($key, $const_replaces)) {
                        $value['value'] = $const_replaces[$key];
                        continue;
                    }
                    $field = substr($key, 1, -1);
                    $value['value'] = isset($arow[$field]) ? $arow[$field] : $value['default'];
                }
                $ssql = $sql;
                preg_match_all('/\{[^\}]+\}/', $sql, $matches); // {parent_id}
                $nmatches = count($matches[0]) - 1;
                foreach ($matches[0] as $key) {
                    $ssql = str_replace($key, $vars[$key]['value'], $ssql);
                }
                echo $ssql, PHP_EOL;
                $ids[] = $i;
                $i++;
                if (array_key_exists('children', $arow)) {
                    $config['var']['{type}']['default'] = 'M';
                    generate_insert_sql($arow['children'], $config, $i, $arow['code']);
                } else if (array_key_exists('O', $arow)) {
                    $config['var']['{type}']['default'] = 'O';
                    generate_insert_sql($arow['O'], $config, $i, $arow['code']);
                    $config['var']['{type}']['default'] = 'M';
                } else if (array_key_exists('E', $arow)) {
                    $config['var']['{type}']['default'] = 'E';
                    generate_insert_sql($arow['E'], $config, $i, $arow['code']);
                    $config['var']['{type}']['default'] = 'M';
                } else if (array_key_exists('F', $arow)) {
                    $config['var']['{type}']['default'] = 'F';
                    generate_insert_sql($arow['F'], $config, $i, $arow['code']);
                    $config['var']['{type}']['default'] = 'M';
                }
            }
        }
        ?>
    </body>
    <script type="text/javascript">
        // fieldset标题点击收起或展开 2014-8-22 by sutroon
        $('legend').attr('title', '点击展开或收起').click(function () {
            $(this).next().toggle();
        })
    </script>
</html>
<?php

function get_addon_combobox($source, $addon) {
    echo '<select onchange="document.getElementById(\'addon\').value=this.value">';
    if ($handle = opendir($source)) {
        while (false !== ( $f = readdir($handle) )) {
            if ('.' == $f || '..' == $f) {
                continue;
            }
            if (is_file($source . '/' . $f . '/Install/module.config.php')) {
                echo '<option value="', $f, '"', ($addon == $f ? 'selected="selected"' : ''), '>', $f, '</option>';
            }
        }
        closedir($handle);
    }
    echo '</select>';
}
?>
